package cool.lichuan.project.common;

import cn.hutool.core.date.DateUtil;
import cool.lichuan.common.domain.Result;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * @author lichuan
 * @date 2021/11/24 16:18
 * @description
 */
@RestController
public class BaseController {
    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtil.parse(text));
            }
        });
    }

    protected Result<Object> toResult(int result) {
        return result > 0 ? success() : error();
    }

    protected Result<Object> toResult(boolean result) {
        return result ? success() : error();
    }

    protected Result<Object> success() {
        return Result.success();
    }

    protected Result<Object> error() {
        return Result.error();
    }
}
